//
//  KYStatus.swift
//  01-我的微博
//
//  Created by apple on 15/8/2.
//  Copyright © 2015年 KY. All rights reserved.
//

import UIKit
import SDWebImage

/// 微博模型
class KYStatus: NSObject {
    
    // MARK: - 微博属性
    /// 微博创建时间
    var created_at: String?
    /// 微博ID`
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    /// 配图数组 -- 字典数组
    var pic_urls: [[String: AnyObject]]?{
        
        didSet{
            if pic_urls!.count == 0 {
                return
            }
            storedPictureURLs = [NSURL]()
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                }
            }
        }
    }
    /// 保存 配图的 URL 数组
    private var storedPictureURLs: [NSURL]?
    
    ///配图数组
    var pictureURLs: [NSURL]?{
        // 如果转发为空 显示原创  否则显示转发的配图

        return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
    }
    /// 显示微博所需要得行高
    var rowHeight: CGFloat?
    
    /// 微博作者的用户信息字段
    var user: KYUser?
    /// 转发微博
    var retweeted_status: KYStatus?
    
    
    
    // MARK: - 构造函数
    /// 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "retweeted_status" {
            
            if let dict = value as? [String: AnyObject]{
            retweeted_status = KYStatus(dict: dict)
            return
        }
        }
        
        if key == "user" {
            if let dict = value as? [String: AnyObject]{
                user = KYUser(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    
    /// 重写 description
    override var description: String {
        let properties = ["created_at", "id", "text", "source", "pic_urls"]
        
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    /// 加载微博数据 返回每个微博数据的数组
    class func loadStatus(finashed: (result: [KYStatus]?, error: NSError?) -> () ) {
        KYNetworkTools.sharedNetworkTools.loadStatuses { (result, error) -> () in
            if error != nil {
                
                finashed(result: nil, error: error)
                return
            }
            
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                var list = [KYStatus]()
                
                for dict in array {
                    list.append(KYStatus(dict: dict))
                }
                cacheWebImage(list, finashed: finashed)
                
            }
            //            finashed(result: nil, error: nil)
        }
//        return
    }
    
    /// 缓存微博到 网络图片 缓存之后 才能刷新数据
    private class func cacheWebImage(list: [KYStatus], finashed:(dataList: [KYStatus]?, error: NSError?) -> ()) {
        
        /// 创建调度组
        let group = dispatch_group_create()
        /// 缓存图片大小
        var dataLength = 0
        // 循环遍历数组
        for status in list {
            
            guard let urls = status.pictureURLs else {
                continue
            }
            
            for imageUrl in urls {
                
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) in
                    if image != nil {
                    let data = UIImagePNGRepresentation(image)!
                 
                    dataLength += data.length
                    }
                    dispatch_group_leave(group)
                    })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存图片\(dataLength/(1024))K")
            finashed(dataList: list, error: nil)
        }
    }
    
    
}
